package com.hnucm.cooklife.base;

import android.annotation.TargetApi;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.SPUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hnucm.cooklife.base.utils.ApiServer;
import com.hnucm.cooklife.base.utils.Constant;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class BaseModel {

    private static final String TAG = "BaseModel";

    //protected 可以给子类用
    protected Retrofit mRetrofit;
    protected ApiServer mApiServer;

//    protected OkHttpClient mOkHttpClient;



    public BaseModel() {
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();
        mRetrofit = new Retrofit.Builder()
                .client(getOkHttpClient())
                .baseUrl(Constant.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonStringConverterFactoryWrapper.create(gson))
                .build();
        mApiServer = mRetrofit.create(ApiServer.class);


    }

    private static OkHttpClient getOkHttpClient(){
        //日志显示级别
        HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;
        //新建log拦截器
        HttpLoggingInterceptor loggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.d(TAG, message);
            }
        });
        loggingInterceptor.setLevel(level);
        //定制OkHttp
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient
                .Builder();
        //OkHttp进行添加拦截器loggingInterceptor
        httpClientBuilder.addInterceptor(loggingInterceptor);
        return httpClientBuilder.build();
    }

    //设置是否保存Cookies
    public void setCookies(boolean isSaveCookies){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(new ReadCookieInterceptor());
        builder.addInterceptor(new WriteCookieInterceptor(isSaveCookies));
        builder.connectTimeout(50000, TimeUnit.MILLISECONDS)
                .readTimeout(50000, TimeUnit.MILLISECONDS);
        mRetrofit = new Retrofit.Builder()
                .client(builder.build())
                .baseUrl(Constant.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        mApiServer = mRetrofit.create(ApiServer.class);
    }

    public class ReadCookieInterceptor implements Interceptor{
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            Request.Builder builder = chain.request().newBuilder();
            long expire = SPUtils.getInstance("cookie").getLong("cookie_expire", 0);
            if(expire > System.currentTimeMillis()){
                String cookies = SPUtils.getInstance("cookie").getString("user");
                if(!TextUtils.isEmpty(cookies)){
                    for (String cookie:
                         cookies.split(";")) {
                        builder.addHeader("Cookie",cookie);
                    }
                    return chain.proceed(builder.build());
                }
            }
            return response;
        }
    }

    public class WriteCookieInterceptor implements Interceptor{

        private boolean mSaveCookie;

        public WriteCookieInterceptor(boolean saveCookie) {
           this.mSaveCookie = saveCookie;
        }

//        @TargetApi(Build.VERSION_CODES.N)
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            if(mSaveCookie){
                List<String> headers = response.headers("Set-Cookie");
                if(!headers.isEmpty()){
                    StringBuilder sb = new StringBuilder();
                    headers.stream().forEach(h ->{
                        sb.append(h).append(";");
                    });
                    SPUtils.getInstance("cookie").put("user", sb.toString());
                    SPUtils.getInstance("cookie").put("cookie_expire", System.currentTimeMillis() + 30 * 24 * 3600 * 1000L);
                }
            }
            return response;
        }
    }
}
